package com.atguigu.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class MyResource{
    public synchronized void m1(){
        System.out.println(Thread.currentThread().getName());
        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
    }


    Lock lock = new ReentrantLock();
    public void m2() throws InterruptedException
    {
//        if(lock.tryLock())
        if(lock.tryLock(1,TimeUnit.SECONDS))
        {
            try
            {
                System.out.println(Thread.currentThread().getName()+"\t"+"---come in");
                //暂停几秒钟线程
                try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }else{
            System.out.println(Thread.currentThread().getName()+"\t"+"---抢锁失败");
        }
    }
}

public class SyncVsReentrantLockDemo {

    public static void main(String[] args) {
        MyResource myResource = new MyResource();
        new Thread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        try {
                            myResource.m2();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }, "t1").start();

        new Thread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        try {
                            myResource.m2();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }, "t2").start();
    }

}
